/*
 *                    COPYRIGHT NOTICE
 *
 *           This code is copyright protected by Freedom Inc.
 *
 *              2001-2012 All Rights Are Reserved
 */
package com.freedom.oldsong.system.dao.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;

import com.freedom.oldsong.system.dao.MenuDao;
import com.freedom.oldsong.system.model.MenuItem;
import com.freedom.oldsong.util.MenuParser;
import com.freedom.oldsong.util.PrivilegeUtil;
import com.thoughtworks.xstream.persistence.FileStreamStrategy;
import com.thoughtworks.xstream.persistence.StreamStrategy;
import com.thoughtworks.xstream.persistence.XmlMap;

/**
 * @author steven.wang
 *
 */
public class MenuDaoImpl implements MenuDao,ServletContextAware {
	
	private ServletContext servletContext;
	
	private String path;
	
	private static List<MenuItem> menus;
	
	/**
	 * get path of meun folder 
	 * @return
	 */
	private String getPath() {
		if (path == null) {
			path = servletContext.getRealPath("/WEB-INF/classes/menus"); 
		}
		return path;
	}
	
	@SuppressWarnings("unchecked")
	private void initMenuItemList() {
		StreamStrategy strategy = new FileStreamStrategy(new File(getPath()));
		menus = new ArrayList<MenuItem>(new XmlMap(strategy).values());
	}

	@Override
	public List<MenuItem> getMenus() {
		List<MenuItem> mis = new ArrayList<MenuItem>();
		if (menus == null) {
			initMenuItemList();
		}
		for(MenuItem mi: menus){
			String roles = mi.getRequiredRoles();
			if(roles!=null&&roles.length()>0&&PrivilegeUtil.hasAnyRole(roles.split(PrivilegeUtil.SEPARATOR))){
				mis.add(mi);
			}
			else{
				String privileges = mi.getRequiredPrivieges();
				if(privileges!=null&&privileges.length()>0&&PrivilegeUtil.hasAnyPrivilege(privileges.split(PrivilegeUtil.SEPARATOR))){
					mis.add(mi);
				}
			}
			
		}
		return mis;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	public MenuItem getMenuByName(String name) {
		File file = new File(getPath() + "/" + name + ".xml");
		return MenuParser.parseMenuItem(file);
	}
}
